package com.purchase.manage.service.impl;

import com.purchase.common.config.PurchaseConfig;
import com.purchase.common.exception.file.InvalidExtensionException;
import com.purchase.common.utils.SecurityUtils;
import com.purchase.common.utils.file.FileUploadUtils;
import com.purchase.common.utils.file.MimeTypeUtils;
import com.purchase.common.utils.uuid.IdUtils;
import com.purchase.manage.damian.DAO.SupplierDAO;
import com.purchase.manage.damian.Supplier;
import com.purchase.manage.mapper.ManagePurchaseMapper;
import com.purchase.manage.mapper.ManageSupplierMapper;
import com.purchase.manage.service.IManageSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
public class ManageSupplierServiceImpl implements IManageSupplierService {

    @Autowired
    ManageSupplierMapper manageSupplierMapper;

    @Autowired
    ManagePurchaseMapper managePurchaseMapper;


    @Override
    @Transactional
    public int checkSupplier(SupplierDAO supplier) throws IOException, InvalidExtensionException {

        if (manageSupplierMapper.checkSupplier(supplier.getHandledByPhone()) !=0){
            throw new SecurityException("新增供应商'" + supplier.getHandledBy() + "'失败，该账号已存在");
        }
        supplier.setSupplierId(IdUtils.randomSnowflake());
        if (supplier.getFile().isEmpty()){
            throw  new SecurityException("上传图片异常");
        }
        String businessLicense = FileUploadUtils.upload(PurchaseConfig.getAvatarPath(), supplier.getFile(), MimeTypeUtils.IMAGE_EXTENSION);
        supplier.setPassword(SecurityUtils.encryptPassword(supplier.getPassword())); //密码加密
        supplier.setBusinessLicense(businessLicense);
        if (managePurchaseMapper.selectCount(supplier.getHandledByPhone()) !=0){
            throw new SecurityException("新增供应商'" + supplier.getHandledBy() + "'失败");
        }
        if (supplier.getTypeIds().length() >250){
            throw new SecurityException("供应商选取类别过多，请重新选择失败");
        }
        if (manageSupplierMapper.insertSupplier(supplier) !=1){
            throw new SecurityException("新增供应商'" + supplier.getHandledBy() + "'失败");
        }
        return 1;
    }

    //修改供应商信息
    @Override
    public void updateSupplier(SupplierDAO supplier) {
        supplier.setSupplierId(supplier.getSupplierId());
        if ( manageSupplierMapper.updateSupplier(supplier) != 1){
            throw new SecurityException("信息更新失败");
        }
    }

    //查看供应商信息
    @Override
    public Supplier selectSupplier(Long sId) {
        Long supplierId = manageSupplierMapper.selectSupplierId(SecurityUtils.getUserId());
        return manageSupplierMapper.selectSupplierById(supplierId);
    }
}
